package com.demo.exceptionHandler;

import net.minidev.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class GlobalSimpleMappingExceptionResolver extends
        SimpleMappingExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response, Object handler, Exception ex) {
        logger.error(request.getRequestURL().toString(), ex);
        String viewName = determineViewName(ex, request);
        response.setContentType("application/json;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resultCode", 1);
        jsonObject.put("resultMessage", "系统异常");
        jsonObject.put("result", ex.toString());
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(jsonObject.toJSONString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("doResolveException", e);
        }
        if (writer != null) writer.close();
        return null;
    }
}